const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {HotModuleReplacementPlugin} = require('webpack')
const MiniCSSExtractPlugin = require('mini-css-extract-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')

module.exports = {
  entry: './src/main.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  mode: 'development',
  devServer: {
    contentBase: './dist',
    hot: true
  },
  module: {
    rules: [
      {
        test: /.css$/,
        use: [
          // 'style-loader',
          MiniCSSExtractPlugin.loader,
          'css-loader'
        ]
      },
      {
        test: /.(png|svg|jpg|jpeg|gif|webp)$/,
        use: {
          loader: 'file-loader',
          options: {
            name: 'img/[name]-[hash:8].[ext]'
          }
        }
      }
    ]
  },
  plugins: [
    // 提取 CSS 文件
    new MiniCSSExtractPlugin({
      filename: '[name]_[contenthash:8].css'
    }),
    // 配置 css 压缩
    new OptimizeCSSAssetsPlugin({
      assetNameRegExp: /\.css$/g,
      cssProcessor: require('cssnano')
    }),
    new HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({
      title: '学习文件压缩',
      template: './index.html',
      minify: {
        html5: true,
        collapseWhitespace: true,
        preserveLineBreaks: false,
        minifyCSS: true,
        minifyJS: true,
        removeComments: true
      }
    })
  ]
}
